package com.example.librarysystem.Service;

import com.example.librarysystem.Dao.BorrowerDao;
import com.example.librarysystem.Dao.CreditDao;
import com.example.librarysystem.entity.Borrower;
import com.example.librarysystem.entity.Credit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.util.List;

@Service("creditService")
public class CreditServiceImpl implements CreditService {
    @Autowired
    private CreditDao creditDao;
    @Autowired
    private BorrowerDao borrowerDao;

    @Override
    public Integer selectCount(){
        return creditDao.selectCount();
    }

    @Override
    public Integer selectIsBreach(int borrowerId){
        return creditDao.selectIsBreach(borrowerId);
    }
    @Override
    public List<Credit> selectByBorrowerId(int borrowerId, int currentPage, int pageSize){
        if(currentPage<=0){
            return null;
        }
        int startCurrentPage=(currentPage-1)*pageSize;        //从第几个数据开始
        int count=selectCount();
        int totalPage=count/pageSize+1;                   //总页数
        if (currentPage>totalPage){
            return null;
        }else{
            return creditDao.selectByBorrowerId(borrowerId, startCurrentPage, pageSize);
        }
    }
    @Override
    public int selectByBorrowerIdCount(int borrowerId){
        return creditDao.selectByBorrowerIdCount(borrowerId);
    }
    @Override
    public List<Credit> selectByBorrowerIdWithoutPage(int borrowerId){
        return creditDao.selectByBorrowerIdWithoutPage(borrowerId);
    }
    @Override
    public Credit selectByBorrowerIdWithBreach(int borrowerId){
        return creditDao.selectByBorrowerIdWithBreach(borrowerId);
    }
    @Override
    @Transactional(timeout = 30)
    public int updateCredit(Credit credit){
        Borrower borrower = borrowerDao.selectById(credit.getBorrowerId());
        borrower.setBreach(credit.getIsBreach());
        borrower.setBreachStart(credit.getBreachStart());
        borrower.setBreachEnd(credit.getBreachEnd());
        borrowerDao.updateBreach(borrower);
        creditDao.updateCredit(credit);
        return 0;
    }
    @Override
    @Transactional(timeout = 30)
    public int insertCredit(Credit credit){
        Borrower borrower = borrowerDao.selectById(credit.getBorrowerId());
        borrower.setBreach(credit.getIsBreach());
        borrower.setBreachStart(credit.getBreachStart());
        borrower.setBreachEnd(credit.getBreachEnd());
        borrowerDao.updateBreach(borrower);
        creditDao.insertCredit(credit);
        return 0;
    }
    @Override
    public List<Credit> selectByEndDate(Date breachEnd){
        return creditDao.selectByEndDate(breachEnd);
    }
}
